<?php

class RBAC {
    /*
     * 检查权限
     */

    public function checkAuthority($roleid, $groupname, $modulename, $actionname) {
        $userid = '';
        $userRoleId = $roleid;
        $model = M('RoleAction');
        $roleids = '';
        $this->getRoleIds($roleids, $userRoleId);
        $inId = substr($roleids, 0, strlen($roleids) - 1);
        /*
        $sql = 'SELECT a.is_state,a.id from ' . C('DB_PREFIX') . 'resource as a,';
        $sql.=C('DB_PREFIX') . 'role_action as b where b.id_action = a.id and ';
        $sql.='b.id_role in(' . $inId . ') and a.group_name="' . $groupname . '" and ';
        $sql.='a.module_name="' . $modulename . '" and a.action_name="' . $actionname . '" group by a.id';
         * 
         */
                $sql = 'SELECT a.* from ' . C('DB_PREFIX') . 'resource as a,';
        $sql.=C('DB_PREFIX') . 'role_action as b where b.id_action = a.id and ';
        $sql.='b.id_role in(' . $inId . ')';
        $returns = $model->query($sql);
        $arr = array();
        foreach($returns as $row){
            $arr[$row['group_name'].':'.$row['module_name']][$row['action_name']] = $row['is_state'];
        }
        dump($returns);
        dump($arr);
       // F('arrList',$arr);
        echo $model->getLastSql();
        if (count($returns) > 0) {
            return true;
        } else {
            $model = M('Resource');
            $map = array(
                'group_name' => $groupname,
                'module_name' => $modulename,
                'action_name' => $actionname,
            );
            //如是1就不受控制
            $state = $model->where($map)->getField('is_state');
            if ($state == 1){
                return true;
            }else{
                return false;
            }
        }
    }

    private function getRoleIds(&$res, $id) {
        $model = M('Role');
        $res .=$id . ',';
        $count = intval($model->where('id=' . $id)->getField('pid'));
        if ($count > 0) {
            $this->getRoleIds($res, $count);
        }
    }

}

?>
